<?php

/**
 *   OPENSHOP 商品库存管理模块
 * 
 *   @link        http://baison.com.cn
 *   @copyright   Baison, Inc.
 *   @package     OpenShop
 *   @version     $Id: inventory_manage.php,v 1.0 2009/06/12 07:35:58 modified $
 *   @author      jiajun <jiajun@baison.com>
 */

define('IN_OS', true);


require(dirname(__FILE__) . '/includes/init.php');

/* act操作项的初始化 */
if (empty($_REQUEST['act']))
{
    $_REQUEST['act'] = 'list';
}else{
    $_REQUEST['act'] = trim($_REQUEST['act']);
}

/*------------------------------------------------------ */
//--商品库存明细列表
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'list' || $_REQUEST['act'] == 'query')
{ 
	/* 权限判断 */
	admin_priv('view_inventory'); 
	$use_storage = empty($_CFG['use_storage']) ? 0 : 1;
	$smarty->assign('use_storage',$use_storage);
	if($use_storage){
		$filter['keyword']=empty($_REQUEST['keyword']) ? '' : trim($_REQUEST['keyword']);
		$where;
		if($filter['keyword'])
			{
			$where.=" And goods_sn like '%".mysql_like_quote($filter['keyword'])."%' or goods_name like '%".mysql_like_quote($filter['keyword'])."%' ";
				}
		$sql_all_goods_number = 'select count(*) from '.$os->table('goods').' where is_delete = 0 '.$where;
    	$count = $db->getOne($sql_all_goods_number);
    	$filter['record_count'] = $count;
    	$filter['from_module'] = 'inventory';		
    	$filter = page_and_size($filter);   
  
    	$goods_inventory_list = goods_all_inventory_list($filter);
 
    	$smarty->assign('goods_inventory_list', $goods_inventory_list);
    	$smarty->assign('filter',       $filter);
    	$smarty->assign('record_count', $filter['record_count']);
    	$smarty->assign('page_count',   $filter['page_count']);
    	$smarty->assign('full_page',    1);
    	$smarty->assign('from_module',  'inventory');
    	
		$action_link = array('href' => 'inventory_manage.php?act=print&page='.$filter['page'], 'text' => '打印商品库存清单');
    	$smarty->assign('action_link',  $action_link);
     
    	if ($_REQUEST['act'] == 'query'){
	   		$smarty->assign('full_page',    0); 
    		make_json_result($smarty->fetch('goods_inventory_all.tpl'), '',
        		array('filter' => $filter, 'page_count' => $filter['page_count']));    	
    	}
	}    		
	/* 赋值到模板 */
    $smarty->assign('ur_here',      '商品库存清单');
    $smarty->assign('full_page',    1);    	
    /* 显示页面 */
    assign_query_info();
    
    $smarty->display("goods_inventory_all.tpl");
}
/*------------------------------------------------------ */
//--特定商品库存明细列表
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'view_inv')
{
	/* 权限判断 */
	admin_priv('view_inventory');
	
	$goods_id = $_REQUEST['id'];
	$goods_sn = $db->getOne("select goods_sn from open_goods where goods_id='".$goods_id."'");
	$goods_inventory_list = goods_inventory_list($goods_id);
    $action_link = array('href' => 'inventory_manage.php?act=print&gid='.$goods_id, 'text' => '打印商品库存清单');		
	$action_link2 = ($_REQUEST['act'] == 'list') ? add_link($code) : array('href' => 'goods.php?act=list', 'text' => '商品列表');
    
	$smarty->assign('action_link',  $action_link);
    $smarty->assign('action_link2',  $action_link2);
    $smarty->assign('use_presale',	$_CFG['use_presale']);
	
	$smarty->assign('from_module',  'inventory');
	$smarty->assign('goods_sn', $goods_sn);

    /* 赋值到模板 */
    $smarty->assign('ur_here',     '['.$goods_sn.']商品库存清单');
    $smarty->assign('full_page',    1);
    
    $goods_inventory = $goods_inventory_list['inventory_list'];
    $size = sizeof($goods_inventory);
    $smarty->assign('size', $size); 
    
    $smarty->assign('is_show_zero_inventory' , $_CFG['is_show_zero_inventory'] ); //0库存是否显示
    $smarty->assign('goods_inventory_list',  $goods_inventory);    
    
    /* 显示页面 */
    assign_query_info();
    
    $smarty->display("goods_inventory.tpl");
}
/*------------------------------------------------------ */
//--商品库存明细列表简短展示
/*------------------------------------------------------ */
elseif($_REQUEST['act'] == 'view_inv_brief')
{
    $goods_id = $_REQUEST['id'];
    $goods_inventory_list = goods_inventory_list($goods_id);
    /* 显示页面 */
    assign_query_info();    
    $goods_inventory = $goods_inventory_list['inventory_list'];
    $size = sizeof($goods_inventory);
    
    $smarty->assign('size', $size);
    $smarty->assign('goods_inventory_list', $goods_inventory);
    $str = $smarty->fetch('goods_inventory_info.tpl');
    $goods[] = array('goods_id' => $goods_id, 'str' => $str);
    make_json_result($goods);
}
/*------------------------------------------------------ */
//--特定商品库存数值设置页面
/*------------------------------------------------------ */
elseif($_REQUEST['act'] == 'set_inv')
{
	admin_priv('set_inventory');
	$goods_inventory = '';

    $goods_id = $_REQUEST['gid'];
    $color_id = $_REQUEST['cid'];
    $size_id  = $_REQUEST['sid'];

	$sql_ini = 'select g.goods_name,s.size_name,c.color_name,"0" as goods_number_actual,"0" as goods_number_available,"0" as goods_number_presale,"0" as goods_number_alert,"0" as onsell_num from '.$os->table('goods_size').' as s,'.$os->table('goods_color').' as c,'.$os->table('goods').' as g where g.goods_id = s.goods_id and s.goods_id = '.$goods_id.' and c.goods_id = '.$goods_id.' and c.color_id = '.$color_id.' and s.size_id = '.$size_id;
    $goods_inventory_1 = $db->getRow($sql_ini);

    $sql_inv =  'SELECT i.goods_number_available,i.goods_number_actual,i.goods_number_presale,i.goods_number_alert,i.onsell_num FROM '.$os->table('goods_inventory').' as i where i.goods_id = '.$goods_id.' and i.color_id = '.$color_id.' and size_id = '.$size_id;
    $goods_inventory_2 = $db->getAll($sql_inv);

    if(sizeof($goods_inventory_2) > 0){
    	$goods_inventory_1['goods_number_available'] = $goods_inventory_2[0]['goods_number_available'];
    	$goods_inventory_1['goods_number_occupancy'] = intval(get_goods_number_in_order($goods_id, $color_id, $size_id));
        $goods_inventory_1['goods_number_actual'] = $goods_inventory_2[0]['goods_number_actual'];
        $goods_inventory_1['goods_number_presale'] = $goods_inventory_2[0]['goods_number_presale'];
        $goods_inventory_1['goods_number_alert'] = $goods_inventory_2[0]['goods_number_alert'];
		$goods_inventory_1['onsell_num'] = $goods_inventory_2[0]['onsell_num'];
    }

    $goods_inventory = $goods_inventory_1;

    $goods_inventory['goods_id'] = $goods_id;
    $goods_inventory['color_id'] = $color_id;
    $goods_inventory['size_id'] = $size_id;

    $action_link = array('href' => 'inventory_manage.php?act=view_inv&id='.$goods_id, 'text' => '该商品库存列表');	
	$action_link2 = array('href' => 'inventory_manage.php?act=list', 'text' => '所有商品库存列表');
    $smarty->assign('action_link',  $action_link);
    $smarty->assign('action_link2',  $action_link2);    
	$smarty->assign('use_presale',	$_CFG['use_presale']);//是否启用商品预售:
//var	onsell_rate_num = 0;
//var	onsell_min_num = 0;
	//$use_presale = $_CFG['use_presale']	; //是否启用商品预售:
	$smarty->assign('onsell_rate_num', $db->getOne("select onsell_rate_num from open_tb_app where is_use=1")) ; 
	$smarty->assign('onsell_min_num',  $db->getOne("select onsell_min_num from open_tb_app where is_use=1")) ; 
    /* 赋值到模板 */
    $smarty->assign('ur_here',      '商品库存设置');
    $smarty->assign('full_page',    1);
    $smarty->assign('inv_act',    'operate_inv');

    /* 显示页面 */
    assign_query_info();

    $smarty->assign('goods_inventory', $goods_inventory);
    $smarty->display("goods_inventory_set.tpl");
}
/*------------------------------------------------------ */
//--商品库存操作明细:库存调整,库存同步
/*------------------------------------------------------ */
elseif($_POST['act'] == 'operate_inv')
{
	/* 权限判断 */
    admin_priv('set_inventory');
    
    $goods_id  = $_POST['goods_id'];
    $color_id  = $_POST['color_id'];
    $size_id  = $_POST['size_id'];
    
    $goods_number_available = $_POST['goods_number_available'];
    $goods_number_actual 	= $_POST['goods_number_actual'];
    $goods_number_presale 	= $_POST['goods_number_presale'];
    $goods_number_alert 	= $_POST['goods_number_alert'];
    
    $onsell_num 	= $_POST['onsell_num'];
    
    $act_flag = $_REQUEST['act_flag'];

    /*
	$sum = get_goods_number_in_order($goods_id, $color_id, $size_id);
    $goods_number_available = $goods_number_actual - $sum;
    */

    $record = get_total_account($goods_id, $color_id, $size_id);

    if($record == 0){
    	$sql_insert = 'insert into '.$GLOBALS['os']->table('goods_inventory').'(goods_id,color_id,size_id,goods_number_actual,goods_number_available,goods_number_presale,goods_number_alert,onsell_num)'
    	              ."VALUES ('$goods_id', '$color_id', '$size_id','$goods_number_actual', '$goods_number_available', '$goods_number_presale', '$goods_number_alert','$onsell_num')";
        $GLOBALS['db']->query($sql_insert);
    }elseif($record == 1){
        $sql_update = 'UPDATE ' . $GLOBALS['os']->table('goods_inventory') .
                      ' SET goods_number_actual = '.$goods_number_actual.', goods_number_available = '.$goods_number_available.', goods_number_presale = '.$goods_number_presale.', goods_number_alert = '.$goods_number_alert.', onsell_num = '.$onsell_num.
                      ' WHERE goods_id = '.$goods_id.' and color_id = '.$color_id.' and size_id = '.$size_id;
        $GLOBALS['db']->query($sql_update);
    }
    

    /* 清除缓存 */
    clear_cache_files(); 
    $link[0]['text'] = '返回该商品库存列表';
	$link[0]['href'] = 'inventory_manage.php?act=view_inv&id='.$goods_id;
	$link[0]['flag'] = 'inventory';
    
    $link[1]['text'] = '返回所有商品库存列表';
	$link[1]['href'] = 'inventory_manage.php?act=list';
	$link[1]['flag'] = 'inventory';

    if ($act_flag == 'syn_inv') {
        sys_msg('商品库存同步成功！', 0, $link);
    }else{
    	sys_msg('商品库存更新成功！', 0, $link);
    }
}
/*------------------------------------------------------ */
//--商品库存删除操作
/*------------------------------------------------------ */
elseif($_REQUEST['act'] == 'del_inv')
{
    /* 权限判断 */
    admin_priv('drop_inventory');

    $goods_id  = $_REQUEST['gid'];
    $color_id  = $_REQUEST['cid'];
    $size_id  = $_REQUEST['sid'];

    $record = get_total_account($goods_id,$color_id,$size_id);

    $link[0]['text'] = '返回该商品库存列表';
    $link[0]['href'] = 'inventory_manage.php?act=view_inv&id='.$goods_id;
    $link[0]['flag'] = 'inventory';
    
    $link[1]['text'] = '返回所有商品库存列表';
    $link[1]['href'] = 'inventory_manage.php?act=list';
    $link[1]['flag'] = 'inventory';    
    
    if($record == 0){
        sys_msg('商品库存表中还没有此条记录,请先设置相应库存数值！', 1, $link);
    }elseif($record == 1){
        $sql_delete = 'delete from ' . $os->table('goods_inventory') .
                      ' where goods_id = '.$goods_id.' and color_id = '.$color_id.' and size_id = '.$size_id;
        $db->query($sql_delete);
        sys_msg('商品库存删除成功！', 0, $link);
    }

    /* 清除缓存 */
    clear_cache_files();
}
/*------------------------------------------------------ */
//--Ajax操作库存数值
/*------------------------------------------------------ */
elseif($_REQUEST['act'] == 'edit_inv_available' || $_REQUEST['act'] ==  'edit_inv_actual' || $_REQUEST['act'] == 'edit_inv_presale' || $_REQUEST['act'] ==  'edit_inv_alert')
{
    /* 权限判断 */
    admin_priv('set_inventory');
        
    $goods_number_available = '';$goods_number_actual = '';$goods_number_presale = '';$goods_number_alert = '';$clause = '';

    $goods_id  = $_POST['id'];
    $color_id  = $_POST['cid'];
    $size_id   = $_POST['sid'];
    $inv_value = intval($_POST['val']);
   
    if($inv_value < 0 && $_REQUEST['act'] != 'edit_inv_actual')
    {
        make_json_error('输入库存数量不符合规范');
    }   
    
    if ($_REQUEST['act'] == 'edit_inv_available') {
    	$goods_number_available = $inv_value;
    	$update_column = 'goods_number_available';    	
    }elseif ($_REQUEST['act'] ==  'edit_inv_actual'){
    	$goods_number_actual = $inv_value;
    	$update_column = 'goods_number_actual';
    }elseif ($_REQUEST['act'] ==  'edit_inv_presale'){
    	$goods_number_presale = $inv_value;
    	$update_column = 'goods_number_presale';
    }elseif ($_REQUEST['act'] ==  'edit_inv_alert'){
    	$goods_number_alert = $inv_value;
    	$update_column = 'goods_number_alert';     		
    }
    
    $record = get_total_account($goods_id,$color_id,$size_id);
    
    if($record == 0){
    	$sql_insert = 'insert into '.$os->table('goods_inventory').'(goods_id,color_id,size_id,goods_number_actual,goods_number_available,goods_number_presale,goods_number_alert)'
    	              ."VALUES ('$goods_id', '$color_id', '$size_id', '$goods_number_actual', '$goods_number_available', '$goods_number_presale', '$goods_number_alert')";
    	              
        if ($db->query($sql_insert)) {
        	clear_cache_files();
        	make_json_result($inv_value);            	
        }
    
    }elseif($record == 1){
        $sql_update = 'UPDATE ' . $os->table('goods_inventory') .
                      ' SET '.$update_column.' = '.$inv_value.$clause.
                      ' WHERE goods_id = '.$goods_id.' and color_id = '.$color_id.' and size_id = '.$size_id;
        if ($db->query($sql_update)){
        	clear_cache_files();
        	make_json_result($inv_value);          	
        }
    }
} 
/*------------------------------------------------------ */
//--商品库存明细列表打印
/*------------------------------------------------------ */
elseif($_REQUEST['act'] == 'print')
{
    /* 权限判断 */
    admin_priv('print_inventory');
    
	$goods_inventory_list = array();$goods_id = '';
    $goods_id  = $_REQUEST['gid'];
    
    // 判断从哪个库存页面进行打印
    if ($goods_id != '') {
    	$inventory_list = goods_inventory_list($goods_id);
    	$goods_inventory_list = $inventory_list['inventory_list'];
    	$size = sizeof($goods_inventory_list);   
    	$smarty->assign('size', $size);      	
    	$tpl = 'inventory_print.html';
    }else{
    	$sql_all_goods_number = 'select count(*) from '.$os->table('goods').' where is_delete = 0 ';
    	$count = $db->getOne($sql_all_goods_number);
    	$filter['record_count'] = $count;
    	$filter['from_module'] = 'inventory';
    	$filter = page_and_size($filter); 
    	$goods_inventory_list = goods_all_inventory_list($filter);  	
    	$tpl = 'inventory_all_print.html';
    }
       
    $smarty->assign('goods_inventory_list', $goods_inventory_list);

    $smarty->template_dir = '../' . DATA_DIR;
    
    $html = $smarty->fetch($tpl).'<div style="PAGE-BREAK-AFTER:always"></div>';     
    echo $html;
    
    exit;                
}

/**
* 获得给定商品库存记录数
*/
function get_total_account ($goods_id, $color_id, $size_id)
{
    $sql_count = 'select count(*) from '.$GLOBALS['os']->table('goods_inventory').' as i where i.goods_id = '.$goods_id.' and i.color_id = '.$color_id.' and size_id = '.$size_id;
    $amount = $GLOBALS['db']->getOne($sql_count);
    return $amount;
}

/**
 * 获得给定商品订单中的数量总数
 */
function get_goods_number_in_order ($goods_id, $color_id, $size_id)
{
    //$sql_goods_number_in_order = 'select sum(g.goods_number) from '.$GLOBALS['os']->table('order_goods').' as g,'.$GLOBALS['os']->table('order_info').' as i where g.order_id = i.order_id and g.goods_id = '.$goods_id.' and g.color_id = '.$color_id.' and g.size_id = '.$size_id.' and ((i.order_status = 0 and i.shipping_status = 0) or (i.order_status = 1 and i.shipping_status = 0) or (i.order_status = 1 and i.shipping_status = 3))';
	$sql_goods_number_in_order = 'select sum(g.goods_number) from '.$GLOBALS['os']->table('order_goods').' as g,'.$GLOBALS['os']->table('order_info').' as i where g.order_id = i.order_id and g.goods_id = '.$goods_id.' and g.color_id = '.$color_id.' and g.size_id = '.$size_id.' and i.shipping_status = 0 and i.order_status = 1' ;
	$sum = $GLOBALS['db']->getOne($sql_goods_number_in_order);
    
    return $sum;
}

/**
 *  返回所有商品库存信息数据
 *
 * @access  public
 * @param
 *
 * @return void
 */
function goods_all_inventory_list($filter)
{
	
	
	$sql = " SELECT goods_id ".
		" FROM " . $GLOBALS['os']->table('goods') . " AS g where is_delete = 0";
	if ($filter['keyword'])
		{
		$sql=$sql." And goods_sn like '%".mysql_like_quote($filter['keyword'])."%' or goods_name like '%".mysql_like_quote($filter['keyword'])."%' ";
		}		
      $sql=$sql." ORDER BY g.goods_id ".
           " LIMIT " . $filter['start'] . ",$filter[page_size]";
    $row = $GLOBALS['db']->getAll($sql);
    
    $result = array();
    foreach ($row AS $key => $value){
    	$goods_inventory = goods_inventory_list($value['goods_id']);
    	$result[$value['goods_id']] = $goods_inventory;
    	$result[$value['goods_id']]['size'] = sizeof($goods_inventory['inventory_list']);
    }
    return $result;
}


/**
 *  返回给定商品库存信息数据
 *
 * @access  public
 * @param
 *
 * @return void
 */
function goods_inventory_list($goods_id){
	$goods_color_size_list = array();$goods_inventory_list = array();$inventory_list = array();

	$sql_goods_color_size = 'select s.goods_id,g.goods_name,s.size_id,s.size_name,c.color_id,c.color_name,"0" as goods_number_actual,"0" as goods_number_available,"0" as goods_number_alert,"0" as goods_number_presale,"0" as onsell_num from '.$GLOBALS['os']->table('goods_size').' as s,'.$GLOBALS['os']->table('goods_color').' as c,'.$GLOBALS['os']->table('goods').' as g where g.goods_id = s.goods_id and s.goods_id = '.$goods_id.' and c.goods_id = '.$goods_id.' order by c.color_id asc,s.size_id asc';
	$goods_color_size_list = $GLOBALS['db']->getAll($sql_goods_color_size);

    $sql_goods_inventory = 'select i.size_id,i.color_id,i.goods_number_actual,i.goods_number_available,i.goods_number_presale,i.goods_number_alert,i.onsell_num from '.$GLOBALS['os']->table('goods_inventory').' as i where i.goods_id = '.$goods_id.' order by i.id asc';
   
    $goods_inventory_list = $GLOBALS['db']->getAll($sql_goods_inventory);
	foreach ($goods_color_size_list AS $key => $value){
	   	$item_1 = $value;
		foreach ($goods_inventory_list AS $key => $value){
			$item_2 = $value;
			if($item_1['size_id'] == $item_2['size_id'] && $item_1['color_id'] == $item_2['color_id']){
				$item_1['goods_number_available'] = $item_2['goods_number_available'];
				$item_1['goods_number_occupancy'] = intval(get_goods_number_in_order($item_1['goods_id'], $item_1['color_id'], $item_1['size_id']));
				$item_1['goods_number_actual'] = $item_2['goods_number_actual'];
				$item_1['goods_number_presale'] = $item_2['goods_number_presale'];
				$item_1['goods_number_alert'] = $item_2['goods_number_alert'];
				$item_1['onsell_num'] = $item_2['onsell_num'];
			}
		}
		array_push($inventory_list,$item_1);
	}
    $arr = array('inventory_list' => $inventory_list);
 
    return $arr;
}
?>